<template>
  <view class="order-form-container">
	  
		<uni-section title="订单名称" type="line" padding>
			<uni-easyinput class="uni-mt-5" trim="all" v-model="form.orderName" :disabled="orderStatus == '2' || orderStatus == '3'" placeholder="请输入订单名称" >
			</uni-easyinput>
		</uni-section>
	
		<uni-section title="订单类型" type="line" padding>
			<uni-data-select
				v-model="form.orderType"
				:localdata="orderTypeList"
				:disabled="orderStatus == '2' || orderStatus == '3'"
			></uni-data-select>
		</uni-section>
	
		<uni-section title="订单价格" type="line" padding>
			<uni-easyinput class="uni-mt-5" trim="all" v-model="form.orderPrice" :disabled="orderStatus == '2' || orderStatus == '3'" placeholder="请输入订单价格" >
			</uni-easyinput>
		</uni-section>
		
		<uni-section title="订单数量" type="line" padding>
			<uni-easyinput class="uni-mt-5" trim="all" v-model="form.number" :disabled="orderStatus == '2' || orderStatus == '3'" placeholder="请输入订单数量" >
			</uni-easyinput>
		</uni-section>
		
		<uni-section title="预估完成时间" type="line" padding>
			<uni-datetime-picker :start="getCurrentDate()" type="date" :clear-icon="false" :disabled="orderStatus == '2' || orderStatus == '3'" v-model="form.planFinishTime" />
		</uni-section>
		
		<uni-section title="收货地址" type="line" padding>
			<uni-easyinput class="uni-mt-5" trim="all" v-model="form.orderAddress" :disabled="orderStatus == '2' || orderStatus == '3'" placeholder="请输入收货地址">
			</uni-easyinput>
		</uni-section>
	
	<uni-section title="选择环节" type="line" :border="true" padding right-icon="arrowright">
		<template v-slot:right>
			<uni-icons v-if="orderStatus != '2' && orderStatus != '3'" @click="addProcess" type="plus-filled" color="#2979ff" size="26"></uni-icons>
		</template>
		
		<view class="selected-processes" v-if="selectedProcesses.length > 0">
      <view class="process-item" v-for="(process, index) in selectedProcesses" :key="process.linkId">
        <text>{{ process.linkName }}</text>
        <input 
          type="digit" 
          placeholder="输入完成天数" 
          v-model.number="process.daysNumber"
					
					:disabled="orderStatus == '2' || orderStatus == '3'"
        />
				<view class="move-icons" @click="moveUp(index)" v-if="orderStatus != '2' && orderStatus != '3'">
					<uni-icons type="arrow-up" size="12"></uni-icons>
				</view>
				<view class="move-icons" @click="moveDown(index)" v-if="orderStatus != '2' && orderStatus != '3'">
					<uni-icons type="arrow-down" size="12"></uni-icons>
				</view>
				
        <button  v-if="orderStatus != '2' && orderStatus != '3'" type="warn" size="mini" @click="removeProcess(index)">删除</button>
      </view>
    </view>
		
	</uni-section>
	
<!-- 	<uni-section title="附件" type="line" style="margin-bottom: 10rpx;">
		<view class="example-body">
			<uni-file-picker limit="5" file-mediatype="all" title="最多选择5个文件"></uni-file-picker>
		</view>
		
	</uni-section> -->
	<uni-section style="padding-bottom: 20rpx;">
		<view class="submit-btn-container">
			<button v-if="orderStatus != '2' && orderStatus != '3'" type="primary" size="mini" @click="submitForm(0)">存草稿</button>
			<button v-if="orderStatus != '2' && orderStatus != '3'" type="primary" size="mini" @click="submitForm(1)">未开始</button>
			<button v-if="orderStatus != '2' && orderStatus != '3'" type="primary" size="mini" @click="submitForm(2)">提交订单</button>
		</view>
	</uni-section>

	<!-- 选择工序弹窗 -->
	<ProcessSelector
		ref="processModal"
		:selectedItems="selectedProcessIds" 
		@confirm="handleConfirmSelection"  
		@selectionChange="selectionChange"  
		@close="handleModalClose" 
	/>
  </view>
</template>

<script>
import ProcessSelector from '/components/ProcessSelector.vue';
import request from '/utils/request.js';
import FileUpload from "/components/FileUpload.vue"
import { isEmpty } from "/utils/utils.js"

export default {
	components: {
		ProcessSelector
	},
  data() {
    return {
			mode: 'add', // 当前模式：add（新增）、view（查看）、edit（编辑）
			orderStatus: '', // 
			isEditMode: false, // 是否处于编辑模式
			isDetailMode: false, // 是否处于详情模式（查看或编辑）
			selectedProcessIds: [],// 选中的工序ID数组
			selectedProcesses: [],// 回显的工序列表（包含完成天数）
      form: {
        orderName: '', // 订单名称
        orderType: '', // 订单类型
        orderPrice: '', // 订单价格
        number: '', // 总数量
				planFinishTime: '', // 计划完成时间
        orderAddress: '', // 收货地址
				orderStatus: '0', // 订单状态 0=草稿,1=未开始,2=已下发,3=已完成
				
        attachments: [], // 附件
				isShowProcess: false,
      },
      orderTypeList: [
			  { text: '打样订单', value: "1" },
			  { text: '大货订单', value: "2" },
			],
			orderId: '',
			isSubmit: false,
    }
  },
  onLoad(options) {
      // 根据路由参数判断页面模式
      if (options.orderId) {
        // 有id参数，进入详情模式
        this.mode = 'edit';
        this.isDetailMode = true;
        this.loadData(options.orderId);
				this.setPageTitle('订单详情');
				this.orderId = options.orderId
				this.orderStatus = options.orderStatus
      } else {
        // 无id参数，进入新增模式
        this.mode = 'add';
        this.isEditMode = true;
        this.setPageTitle('发起订单');
      }
    },
  methods: {
		getCurrentDate() {
			const date = new Date();
			const year = date.getFullYear();
			const month = String(date.getMonth() + 1).padStart(2, '0');
			const day = String(date.getDate()).padStart(2, '0');
			return `${year}-${month}-${day}`;
		},
		// 设置页面标题
		setPageTitle(title) {
			uni.setNavigationBarTitle({
				title: title
			});
		},
    loadData(id) {
			request.get(`/system/initiate/${id}`).then(res => {
			  uni.hideLoading()
			  if (res.code === 200) {
					this.form.orderName = res.data.orderName
					this.form.orderType = res.data.orderType
					this.form.orderPrice = res.data.orderPrice
					this.form.number = res.data.number
					this.form.planFinishTime = res.data.planFinishTime
					this.form.orderAddress = res.data.orderAddress
					this.form.orderStatus = res.data.orderStatus
					this.form.attachments = []
					this.selectedProcesses = res.data.orderLinkRealizeList.map((v, index) => {
						return {
							...v,
							linkOrder: index,
						}
					})
					this.selectedProcessIds =  this.selectedProcesses.filter(v => v.linkId !== -1);
					// this.orderId = res.data.orderId
			  } else {
			    uni.showToast({
			      title: res.msg,
			      icon: 'none'
			    })
			  }
			})
		},
		// 新增环节
		addProcess() {
			this.$refs.processModal.open();
		},
    
    // 向上移动工序
		moveUp(index) {
			if (index <= 0) return; // 已经是第一个，无法上移
			
			// 交换数组中当前元素与前一个元素的位置
			[this.selectedProcesses[index], this.selectedProcesses[index - 1]] = 
			[this.selectedProcesses[index - 1], this.selectedProcesses[index]];
			
			// 更新排序号（从0开始）
			this.selectedProcesses.forEach((process, idx) => {
					process.linkOrder = idx;
			});
		},
    // 向下移动工序
		moveDown(index) {
			if (index >= this.selectedProcesses.length - 1) return; // 已经是最后一个，无法下移
			
			// 交换数组中当前元素与后一个元素的位置
			[this.selectedProcesses[index], this.selectedProcesses[index + 1]] = 
			[this.selectedProcesses[index + 1], this.selectedProcesses[index]];
			
			// 更新排序号（从0开始）
			this.selectedProcesses.forEach((process, idx) => {
					process.linkOrder = idx;
			});
		},
    
    // 选择附件
    chooseAttachment() {
      uni.chooseFile({
        count: 5, // 最多可选择文件数量
        success: (res) => {
          this.form.attachments = res.tempFiles;
        }
      })
    },
    
    // 移除附件
    removeAttachment(index) {
      this.form.attachments.splice(index, 1);
    },
    
    // 提交表单
    submitForm(type) {
			if (this.isSubmit) {
				return
			}
			
			this.form.orderStatus = type
			
			//校验必填项
			if (isEmpty(this.form.orderName)) {
				uni.showToast({
					title: `请输入订单名称`,
					icon: 'error',
				})
				return
			}
			if (isEmpty(this.form.orderType)) {
				uni.showToast({
					title: `请选择订单类型`,
					icon: 'error',
				})
				return
			}
			
			if (isEmpty(this.form.number)) {
				uni.showToast({
					title: `请输入总数量`,
					icon: 'error',
				})
				return
			}
			if (!this.validate(this.selectedProcesses, 'daysNumber')) {
				uni.showToast({
					title: `请检查完成天数`,
					icon: 'error',
				})
				return
			}
			
      uni.showLoading({
        title: '提交中...',
      })
			// "0=草稿,1=未开始,2=已下发,3=已完成"
      let params = {
        orderStatus: type,
        ...this.form,
				orderLinkRealizeList: this.selectedProcesses
      }
			if (this.mode === 'edit') {
				params.id = this.orderId
				request.put(`/system/initiate`, params).then(res => {
				  uni.hideLoading()
				  if (res.code === 200) {
				    
						// 跳转到订单列表页
						// uni.navigateTo({
						// 	url: '/pages/workorder/orderList'
						// })
						
						uni.showToast({
						  title: '操作成功',
						  icon: 'success',
						  duration: 1500, // 显示2秒
						});
						this.isSubmit = true
						// 等待提示框显示完成后再跳转
						setTimeout(() => {
						  uni.switchTab({
						    url: `/pages/tabBar/index/index`
						  });
						}, 1500);
						
				  } else {
				    uni.showToast({
				      title: res.msg,
				      icon: 'none'
				    })
				  }
				})
				return
			}
      request.post('/system/initiate', params).then(res => {
        uni.hideLoading()
        if (res.code === 200) {
          uni.showToast({
            title: '提交成功',
            icon: 'success'
          })
					// 跳转到订单列表页
					// uni.navigateTo({
					// 	url: '/pages/workorder/orderList'
					// })
					
					uni.redirectTo({
						url: '/pages/workorder/orderList'
					})
					
        } else {
					
          uni.showToast({
            title: res.msg,
            icon: 'none'
          })
        }
      })
    },
		
		// 处理确认选择
		handleConfirmSelection(selectedItems) {
			// 根据选中的ID获取完整工序信息，并初始化完成天数
			// this.selectedProcesses = [...selectedItems]
			this.selectedProcesses = selectedItems.map((v, index) => {
				return {
					...v,
					daysNumber: v.daysNumber ? v.daysNumber : 15,
					linkOrder: index
				}
			})

      console.log(this.selectedProcesses, '---111')
			// 更新选中ID数组
			this.selectedProcessIds =  this.selectedProcesses.filter(v => v.linkId !== -1);
			uni.showToast({
				title: `已选择 ${selectedItems.length} 个工序`,
				icon: 'success'
			});
		},
		
		// 处理弹窗关闭
		handleModalClose() {
			console.log('弹窗已关闭');
		},
		
		// 移除选中的工序
		removeProcess(index) {
			const process = this.selectedProcesses[index];
			this.selectedProcesses.splice(index, 1);
			
			// 更新选中ID数组
			this.selectedProcessIds =  this.selectedProcesses.filter(v => v.linkId !== process.linkId);
		},
		
		selectionChange(ids) {
			this.selectedProcessIds = ids
		},
		
		// 验证完成天数输入
		validate(arr, prop) {
		  if (!Array.isArray(arr) || arr.length === 0) return false;
			// 正则表达式：匹配整数或浮点数（正数/负数）
			const numberRegex = /^-?\d+(\.\d+)?$/;
			
			// 使用普通for循环替代every
			for (let i = 0; i < arr.length; i++) {
				const item = arr[i];
				
				// 检查属性是否存在且值不为空
				if (!item.hasOwnProperty(prop) || item[prop] == null || item[prop] === '') {
					return false;
				}
				
				// 将值转换为字符串进行正则校验
				const valueStr = String(item[prop]);
				
				// 使用正则判断是否为数字，不通过则立即返回false
				if (!numberRegex.test(valueStr)) {
					return false;
				}
			}
			
			// 所有项都通过校验返回true
			return true;
		}

	},
}
</script>

<style scoped lang="scss">
.order-form-container {
  padding: 20rpx;
}
.uni-form-item {
  margin-bottom: 20rpx;
  display: flex;
  flex-direction: column;
}
.uni-label {
  font-size: 28rpx;
  margin-bottom: 10rpx;
}
.uni-input {
  padding: 15rpx;
  border: 1px solid #ccc;
  border-radius: 6rpx;
  font-size: 28rpx;
  min-height: 50rpx;
}
.attachment-list {
  margin-top: 10rpx;
}
.attachment-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10rpx 0;
  border-bottom: 1px solid #eee;
}
.close-icon {
  color: #999;
  font-size: 24rpx;
  padding: 5rpx;
  cursor: pointer;
}
.uni-button {
  margin-top: 20rpx;
}





/* 底部按钮 */
.modal-footer {
  display: flex;
  border-top: 1px solid #eee;
}
.cancel-btn, .confirm-btn {
  flex: 1;
  padding: 25rpx 0;
  text-align: center;
  font-size: 30rpx;
}
.cancel-btn {
  color: #333;
}
.confirm-btn {
  color: #007aff;
  font-weight: bold;
  border-left: 1px solid #eee;
}
.foot-sumbit {
  position: fixed;
  bottom: 30rpx;
  left: 50%;
  transform: translateX(-50%);
  width: 90%;
  max-width: 680rpx;
  padding: 20rpx 0;
  font-size: 32rpx;
  border-radius: 40rpx;
  box-shadow: 0 -4rpx 20rpx rgba(0, 122, 255, 0.15);
  z-index: 999;
  
  /* 适配底部安全区 */
  /* padding-bottom: constant(safe-area-inset-bottom); */
  /* padding-bottom: env(safe-area-inset-bottom); */
}

/* 表单容器样式调整 */
.order-form-container {
  padding: 20rpx;
  padding-bottom: 220rpx; /* 增加底部内边距，避免内容被按钮遮挡 */
  
  /* 动态计算底部内边距（替代固定值，更灵活） */
  padding-bottom: calc(120rpx + constant(safe-area-inset-bottom));
  padding-bottom: calc(120rpx + env(safe-area-inset-bottom));
}

/* 兼容非全面屏设备的备用方案 */
:root {
  --bottom-space: 160rpx;
}
.order-form-container {
  padding-bottom: var(--bottom-space);
}

/* 针对不同设备的动态调整（JS控制） */
@media screen and (min-device-height: 812px) and (-webkit-device-pixel-ratio: 3) {
  :root {
    --bottom-space: 180rpx; /* iPhone X系列等全面屏设备 */
  }
}
@media screen and (min-device-height: 896px) and (-webkit-device-pixel-ratio: 3) {
  :root {
    --bottom-space: 200rpx; /* iPhone 12/13系列等全面屏设备 */
  }
}

/* 回显区域样式 */
.selected-processes {
  margin-top: 10rpx;
  .process-item {
    display: flex;
    align-items: center;
    padding: 6rpx 10rpx;
		margin-top: 6rpx;
    border: 2rpx solid #eee;
    
    text {
      flex: 1;
    }
    
    input {
      flex: 1;
      border: 1px solid #eee;
      border-radius: 4px;
      padding: 5px 10px;
      margin: 0 10px;
    }
  }
}

.submit-btn-container {
	display: flex;
	padding-bottom: 40rpx;
}

.move-icons {
	font-size: 13px;
	line-height: 2.3;
	color: #fff;
	-webkit-tap-highlight-color: transparent;
	background-color: #f8f8f8;
	border-radius: 5px;
	box-sizing: border-box;
	color: #000;
	cursor: pointer;
	display: block;
	margin-left: auto;
	margin-right: auto;
	overflow: hidden;
	padding-left: 7px;
	padding-right: 7px;
	position: relative;
	text-align: center;
	text-decoration: none;
	margin-right: 10rpx;
}

.move-icons uni-icons {
	
}
</style>
